#!/bin/bash
TOMCAT_PATH='/home/linux_7220765146/Tomcat9/apache-tomcat-9.0.98'
EXAM_PATH='/home/linux_7220765146/Exam'
CP="${TOMCAT_PATH}/lib/servlet-api.jar"

# 添加 Exam/lib 中的所有 JAR 包到类路径
for jar_file in "$EXAM_PATH/lib"/*.jar; do
    CP="$CP:$jar_file"
done

# 创建 target 目录
mkdir -p "$EXAM_PATH/target"

# 步骤1: 编译所有 Java 文件
echo "正在编译 Java 文件..."
javac -cp "$CP" "$EXAM_PATH/code"/*.java -d "$EXAM_PATH/target"
if [ $? -ne 0 ]; then
    echo "编译失败"
    exit 1
fi
echo "编译成功"

# 步骤2: 部署到 Tomcat
echo "正在部署类文件..."
cp -r "$EXAM_PATH/target/"* "$TOMCAT_PATH/webapps/ROOT/WEB-INF/classes/"
if [ $? -ne 0 ]; then
    echo "部署失败"
    exit 1
fi
echo "部署成功"

# 步骤3: 重启 Tomcat
echo "正在重启 Tomcat..."
sudo fuser -k 8080/tcp
sleep 2
"$TOMCAT_PATH/bin/shutdown.sh" > /dev/null 2>&1
sleep 3
"$TOMCAT_PATH/bin/startup.sh" > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "Tomcat 重启失败"
    exit 1
fi
echo "Tomcat 重启成功"

echo "部署完成"
tail -f "$TOMCAT_PATH/logs/catalina.out"
